/*
 * @Author: szx
 * @Date: 2022-04-12 13:27:14
 * @LastEditTime: 2022-04-12 13:38:22
 * @Description:
 * @FilePath: \leetcode\剑指offerII\053\053.js
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
var inorderSuccessor = function (root, p) {
    let prev = null;
    let res = null;
    const dfs = (root) => {
        root.left && dfs(root.left);
        if (prev == 1) {
            res = root;
            prev = 2;
            return;
        }
        if (p == root) prev = 1;
        root.right && dfs(root.right);
    };
    dfs(root);
    return res;
};

var inorderSuccessor = function (root, p) {
    let cur = root;
    let result = null;
    while (cur) {
        if (cur.val > p.val) {
            result = cur;
            cur = cur.left;
        } else {
            cur = cur.right;
        }
    }
    return result;
};
